package blackstar.agent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import blackstar.agent.event.BeforeShutdownEvent;
import blackstar.agent.event.EventDispatcherSupport;
import blackstar.agent.event.EventListener;
import blackstar.agent.event.ShutdownEvent;
import blackstar.agent.event.StartupEvent;

/**
 * @author RayWoo (ayufox@gmail.com)
 * 
 */
public class ShutdownHook extends EventDispatcherSupport implements
		EventListener<StartupEvent>
{
	private final static Log LOGGER = LogFactory.getLog(ShutdownHook.class);

	private static boolean isShutdown = false;;

	public Class[] events()
	{
		return new Class[]
		{ StartupEvent.class };
	}

	public void onEvent(StartupEvent event) throws Exception
	{
		Runtime.getRuntime().addShutdownHook(new Thread()
		{
			public void run()
			{
				synchronized (ShutdownHook.class)
				{
					if (!isShutdown)
					{
						LOGGER.info("Dispatch BeforeShutdown");
						dispatch(new BeforeShutdownEvent());
						LOGGER.info("Dispatch Shutdown");
						dispatch(new ShutdownEvent());
						LOGGER.info("Shutdown Success");
						isShutdown = true;
					}
					else
					{
						LOGGER.error("Duplicate Shutdown");
					}
				}
			}
		});
	}
}
